import fsPromises from 'fs/promises'

async function main() {
  const text = await fsPromises.readFile('./1754541669665-error-firstJson提取失败.txt', 'utf-8')

  console.log('text', text)

  const json = extractJsons(text)

  console.log('json', json)
}

main()

function extractJsons(str) {
  // 1. 过滤掉 {insert_element_X_} 占位符
  str = str.replace(/\{insert\\_element\\_\d+\\_\}/g, '')

  // 尝试修复非法转义
  str = str.replace(/\\_/g, '_')
  str = str.replace(/\\N/g, '\\\\N')

  // 查找所有可能包含JSON的部分
  const jsonRegex = /{(?:[^{}]|{(?:[^{}]|{[^{}]*})*})*}/g
  const jsonMatches = str.match(jsonRegex) || []

  console.log('jsonMatches', jsonMatches)

  // 解析两个 JSON
  let firstJson = JSON.parse(jsonMatches[0])
  let secondJson = JSON.parse(jsonMatches[1])

  // 组合成目标对象
  return {
    extract: firstJson.extract || firstJson, // 兼容两种格式
    score: secondJson.score,
  }
}
